const app=getApp();
let _self;
Page({
  data: {
    carts:[],
    allSelector:true,
    total:0,
  },
  onLoad: function (options) {

  },
  onShow: function () {
    _self=this;
    _self.setData({carts:app.globalData.carts});
    this.computeOrder();
    this.setTabBar();
  },
  allSelector:function(event){
    let bool=this.data.allSelector;
    this.setData({allSelector:!bool});
    let shoppingCarts=this.data.carts;
    shoppingCarts.forEach(element=>element.selected=!bool);
    this.setData({carts:shoppingCarts});
    this.computeOrder();
  },
  productSelector:function(event){
    let currentId=event.currentTarget.dataset.id;
    let shoppingCarts=this.data.carts;
    let select=shoppingCarts.find(element => element.id == currentId).selected;
    shoppingCarts.find(element => element.id == currentId).selected=!select;
    if(shoppingCarts.every(element=>element.selected==false)){
      this.setData({allSelector:false});
    }else{
      this.setData({ allSelector: true });
    }
    this.setData({carts:shoppingCarts});
    this.computeOrder();
  },
  addOperation:function(event){
    let currentId=event.currentTarget.dataset.id;
    let shoppingCarts=this.data.carts;
    shoppingCarts.find(element=>element.id==currentId).count++;
    this.setData({carts:shoppingCarts});
    this.computeOrder();
    this.setTabBar();
  },
  reduceOperation:function(event){
    _self=this;
    let currentId = event.currentTarget.dataset.id;
    let shoppingCarts = this.data.carts;
    if (shoppingCarts.find(element => element.id == currentId).count>1){
      shoppingCarts.find(element => element.id == currentId).count--;
      _self.setData({ carts: shoppingCarts });
      _self.computeOrder();
      _self.setTabBar();
    }else{
      wx.showModal({
        title: '',
        content: `确定不要这个菜品了吗？`,
        success:res=>{
          if(res.confirm){
            let currentIndex = shoppingCarts.findIndex(element => element.id == currentId); //查寻数组中的下标
            shoppingCarts.splice(currentIndex, 1); //从数组中删除数据，第一个参数是开始删除的位置（下标），第二个参数是数量。
            _self.setData({ carts: shoppingCarts });
            _self.computeOrder();
            _self.setTabBar();
          }
        }
      });
    }
  },
  computeOrder: function () {
    let shoppingCarts = this.data.carts;
    let tempTotal = 0;
    tempTotal=shoppingCarts.filter(elem=>elem.selected).reduce((prve,elem)=>prve+elem.count*elem.real,0);
    this.setData({ total: tempTotal });
  },
  account:function(){
    wx.showToast({
      title: '成功',
      icon:'success',
      duration:2000
    })
  },
  setTabBar:function(){
    wx.setTabBarBadge({
      index: 1,
      text: this.data.carts.length.toString(),
    })
  }
})